import Taro, { Component } from '@tarojs/taro';
import { View, Text, Button } from '@tarojs/components';
import Line from './img/line.png';
import Shop from './img/icon_shop.png';
import Right from './img/icon_right.png';
import Address from './img/icon_address.png';
import './index.scss';
import { tempOrder, orderConfirm, orderPay, testPay } from '../../../services/order';
import NavigationBar from '../../../components/navigationBar/index';

import { fullImgUrl, timeFormat } from '../../../utils/utils';

export default class Index extends Component {
  config = {
    navigationBarTitleText: '结算中心',
  };

  state = {
    tempOrderInfo: null,
    navigationBarHeight: Taro.getStorageSync('navigationBarHeight'),
    code: '',
    deliveryTime: '',
  };

  componentWillMount() {
    let date = new Date();
    date.setDate(date.getDate() + 1);
    // 下午三点半以后，后天再发货
    if (date.getHours() > 15 || (date.getHours() === 15 && date.getMinutes() >= 30)) {
      date.setDate(date.getDate() + 1);
    }
    let resultData = timeFormat(parseInt(date.getTime() / 1000, 10), 'yyyy年MM月dd日');

    this.setState(
      {
        code: this.$router.params.code || '',
        deliveryTime: Taro.getStorageSync('deliveryTime') || resultData,
      },
      () => {
        Taro.removeStorageSync('deliveryTime');
      }
    );
  }
  componentDidMount() { }
  componentWillReceiveProps(nextProps, nextContext) { }
  componentWillUnmount() { }
  componentDidShow() {
    this.init();
  }
  componentDidHide() { }
  componentDidCatchError() { }
  componentDidNotFound() { }

  init() {
    tempOrder().then(res => {
      if (!res.address) {
        Taro.showToast({
          title: '当前未设置默认地址，请先设置默认地址',
          icon: 'none',
        });
        setTimeout(() => {
          Taro.navigateTo({
            url: '/subPackageWork/pages/my-address/index?isEdit=1',
          });
        }, 2000);
      }
      this.setState({
        tempOrderInfo: res,
      });
    });
  }

  editAddress() {
    Taro.navigateTo({
      url: '/subPackageWork/pages/my-address/index?isEdit=1',
    });
  }

  confirmOrder() {
    if (!this.state.tempOrderInfo.paid_amount) {
      if (this.state.tempOrderInfo.order_type === 5) {
        orderConfirm({
          exchange_no: code,
          card_no: Taro.getStorageSync('card_no'),
          delivery_time: deliveryTime,
        }).then(res => {
          Taro.removeStorageSync('card_no');
          Taro.showToast({
            title: '兑换成功',
            icon: 'success',
          });
          setTimeout(() => {
            Taro.redirectTo({
              url: '/pages/my-order/index',
            });
          }, 1500);
        });
      } else {
        // 订阅通知授权
        // 卡券提货
        // 1. 成功提货通知 TUK6_KyrBuZfoV6MOAdKk-O_BICrgCxy3WUDHnIr_dY
        // 2. 发货通知 m_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ
        // 3. 收货通知 1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g
        var code = this.state.code;
        var deliveryTime = this.state.deliveryTime;
        Taro.requestSubscribeMessage({
          tmplIds: ['TUK6_KyrBuZfoV6MOAdKk-O_BICrgCxy3WUDHnIr_dY', 'm_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ', '1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g'],
          complete: function (subRes) {
            orderConfirm({
              exchange_no: code,
              card_no: Taro.getStorageSync('card_no'),
              delivery_time: deliveryTime,
            }).then(res => {
              Taro.removeStorageSync('card_no');
              Taro.showToast({
                title: '兑换成功',
                icon: 'success',
              });
              setTimeout(() => {
                Taro.redirectTo({
                  url: '/pages/my-order/index',
                });
              }, 1500);
            });
          },
        });
      }
      if (this.state.tempOrderInfo.order_type != 5) {

      }
    } else {
      // 订阅通知授权
      // 下单购买
      // 1. 新订单通知 dTw-cUo1WdE88M41QcPl6S6XFn0THY0lBkoUyOdjupQ
      // 2. 发货通知 m_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ
      // 3. 收货通知 1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g
      var deliveryTime = this.state.deliveryTime;
      Taro.requestSubscribeMessage({
        tmplIds: ['dTw-cUo1WdE88M41QcPl6S6XFn0THY0lBkoUyOdjupQ', 'm_foxsZTKbetdGl2r5B6OK2uO_Car5kwpLiO-mnYvSQ', '1E1WejxNbO3B1mNUUMZIyr1XLccf76KKUDJFJBWd21g'],
        complete: function (subRes) {
          orderConfirm({
            delivery_time: deliveryTime,
          }).then(res => {
            orderPay({
              order_id: res.order_info_id,
              pay_type: 3, // 连连支付
              // pay_type: 1,
              pay_platform: 1,
            }).then(data => {
              Taro.requestPayment({
                ...JSON.parse(data.payload).metadata,
                // ...data,
                success() {
                  Taro.redirectTo({
                    url: '/pages/my-order/index',
                  });
                },
                fail() {
                  Taro.redirectTo({
                    url: '/pages/my-order/index',
                  });
                },
              });
            });
          });
        },
      });
    }
  }

  add() {
    // this.setState({
    //   goodsNum: this.state.goodsNum + 1
    // })
  }

  cut() {
    // this.setState({
    //   goodsNum: this.state.goodsNum - 1
    // })
  }

  render() {
    const { tempOrderInfo, code, deliveryTime } = this.state;
    return tempOrderInfo ? (
      <View className='order-detail' style={`margin-top: ${navigationBarHeight}`}>
        <NavigationBar text='结算中心' />

        <View className='user-wrapper' onClick={this.editAddress}>
          <View className='address-name'>收货地址:</View>
          <View className='user-info'>
            <View className='username'>{tempOrderInfo.address.receiver}</View>
            <View className='tel'>{tempOrderInfo.address.mobile}</View>
          </View>
          <Image className='left' src={Address} alt='地址' />
          <View className='address-info'>
            {tempOrderInfo.address.province_name}
            {tempOrderInfo.address.city_name}
            {tempOrderInfo.address.region_name}
            {tempOrderInfo.address.address}
          </View>
          <Image className='right' src={Right} alt='编辑地址' />
          <Image className='line' src={Line} alt='line' />
        </View>
        <View className='goods-wrapper'>
          <View className='goods-branch'>
            <Image className='icon' src={Shop} alt='店铺' />
            <View className='branch-name'>中鹿岛</View>
          </View>
          <View className='goods-detail'>
            <Image
              className='goods-image'
              src={fullImgUrl(tempOrderInfo.goods[0].sku.cover)}
              alt='商品图'
            />
            <View className='goods-info'>
              <View className='goods-name'>{tempOrderInfo.goods[0].sku.goods_name}</View>
              <View className='goods-desc'>
                <View className='item'>{tempOrderInfo.card.attr_name}</View>
                <View className='item'>
                  {tempOrderInfo.goods[0].attr.map(item => {
                    return item.goods_sku_attr_name + ' ';
                  })}
                </View>
              </View>
              <View className='goods-specification'>
                <View className='goods-price'>{tempOrderInfo.goods[0].sku.price}</View>
              </View>
            </View>
          </View>
          {/* <View className="goods-money">
            <View className="text">商品金额</View>
            <View className="money">¥998</View>
          </View> */}
          <View className='should-pay'>
            <View className='text'>数量</View>
            <View className='number-opt'>
              <View className='min' onClick={this.cut}>
                {' '}
                -{' '}
              </View>
              <View>{tempOrderInfo.goods[0].num}</View>
              <View className='add' onClick={this.add}>
                {' '}
                +{' '}
              </View>
            </View>
          </View>
        </View>
        <View className='order-info'>
          <View className='item'>
            <View>商品金额</View>
            <View>{code ? '兑换卡兑换' : `￥${tempOrderInfo.goods_amount}`}</View>
          </View>
          <View className='item'>
            <View>运费</View>
            <View>￥{tempOrderInfo.shopping_fee}</View>
          </View>
          <View className='item'>
            <View>优惠金额</View>
            <View>￥{tempOrderInfo.act_discount}</View>
          </View>
          {deliveryTime && (
            <View className='item'>
              <View>发货时间</View>
              <View>{deliveryTime}</View>
            </View>
          )}
        </View>
        {!tempOrderInfo.paid_amount ? (
          <View className='order-opt'>
            <View></View>
            <View className='opt-btn to-pay' onClick={this.confirmOrder}>
              立即兑换
            </View>
          </View>
        ) : (
          <View className='order-opt'>
            <View className='price'>￥{tempOrderInfo.paid_amount}</View>
            <View className='opt-btn to-pay' onClick={this.confirmOrder}>
              微信支付
            </View>
          </View>
        )}
      </View>
    ) : (
      <View></View>
    );
  }
}
